#include "mytcpsocket.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
#include "sqlmain.h"

MyTcpSocket::MyTcpSocket(QObject *parent)
    : QTcpSocket{parent}
{
    connect(this, &MyTcpSocket::readyRead,
            this, &MyTcpSocket::readyReadSlot);
    connect(this, &MyTcpSocket::dataReceiveSig,
            this, &MyTcpSocket::sendDataToAll);
}

MyTcpSocket::~MyTcpSocket()
{

}

void MyTcpSocket::sendDataToAll(const QByteArray &data)
{
    if(this->state() != MyTcpSocket::ConnectedState)
        return;
    this->write(data);
}

void MyTcpSocket::myAbortSlot()
{
    this->abort();
}

void MyTcpSocket::readyReadSlot()
{
    QByteArray data = this->readAll();
    int count = 0;  //当前括号数量
    int start = -1; //开始的索引
    for(int i = 0; i < data.length(); i++)
    {
        if(data.at(i) == '{')
        {
            count++;
            if(start == -1)
            {
                start = i;
            }
        }
        else if(data.at(i) == '}')
        {
            count--;
            if(count == 0)
            {
                QByteArray temp = data.mid(start, i-start+1);
                start = -1;
                QJsonObject obj = QJsonDocument::fromJson(temp).object();
                handleFrame(obj);
            }
        }
    }
}
